import {
	RSA,
	AES
} from '@/utils/encryption/encrypt-tools.js'

/*
 * 全局请求封装
 * @param path 请求路径
 * @param method 请求类型(GET/POST/DELETE等)
 * @oaram data 请求体数据
 * @param loading 请求未完成是是否显示加载中，默认为true
 */
export default (path, method, data = {}, needToken = true, loading = true) => {
	// 获取存储token
	const token = uni.getStorageSync("token");

	if (loading) {
		uni.showLoading({
			title: "正在加载",
			mask: true
		});
	};
	//根据token进行调用函数
	if (needToken == true) {
		return tokenRequest(path, method, data, loading, token)
	} else {
		return noTokenRequest(path, method, data, loading)
	}
};

// 无token时发送请求函数
function noTokenRequest(path, method, data, loading) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: path,
			method: method,
			data,
			success(response) {
				console.log('%c无Token请求，响应拦截：', ' background:green', path, response);
				/* if (response.data.code === 3001) {
					// logout()
				} */
				/* if (response.data.code !== 20) {
					uni.showToast({
						icon: "none",
						duration: 4000,
						title: response.data.msg
					});
				} */
				console.log(response.data)
				resolve(response.data);
			},
			fail(err, res) {
				uni.showToast({
					icon: "none",
					title: '服务响应失败'
				});
				console.error('noTokenRequest', err);
				console.info('noTokenRequest', res);
				reject(err);
			},
			complete() {
				uni.hideLoading();
			}
		});
	});
}

// 有token时发送请求函数
function tokenRequest(path, method, data, loading, token) {
	let secretKey = uni.getStorageSync('secretKey')
	let iv = uni.getStorageSync('iv')
	let aes = new AES()
	aes.secretKey = secretKey
	aes.iv = iv
	console.log('请求路径：', path)
	console.log('请求Token：', token)
	console.log('请求参数：', data)
	let params = aes.encrypt(JSON.stringify(data))
	return new Promise((resolve, reject) => {
		uni.request({
			url: path,
			method: method,
			withCredentials: true,
			data: params,
			header: {
				"token": token
			},
			timeout: 10000,
			success(response) {
				console.debug('%c响应拦截：', ' background:green', path, response);
				if (response.statusCode === 401) {
					uni.setStorageSync('token', '')
					//Token令牌超时
					uni.showModal({
						title: '提示',
						content: '您的Token令牌已失效，请重新授权登录！',
						confirmText: '去授权登陆',
						success: function(res) {
							if (res.confirm) {
								uni.reLaunch({
									url: '/pages/index/index'
								})
							} else if (res.cancel) {

							}
						}

					})
				} else {
					if (response.statusCode !== 200) {
						console.error('网络请求错误[%c][%d]', path, response.statusCode, data)
					}
					resolve(response.data);
				}
			},
			fail(err) {
				uni.showToast({
					icon: "none",
					title: '服务响应失败'
				});

				reject(err);

			},
			complete() {
				uni.hideLoading();
			}
		});
	});
}